package com.dz.template;

import com.dz.StorageTemplate;
import com.dz.properties.StorageProperties;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.MimeTypeUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Slf4j
@Data
public class MinioTemplate implements StorageTemplate {
    @Autowired
    private StorageProperties minioProperties;

    /**
     * 文件上传
     */
    @Override
    public String uploadFile(MultipartFile file) {
        String endpoint = minioProperties.getEndpoint();
        String accessKeyId = minioProperties.getAccessKeyId();
        String accessKeySecret = minioProperties.getAccessKeySecret();
        String bucketName = minioProperties.getBucketName();
        // 原始文件名
        String originalFilename = file.getOriginalFilename();
        // 截取原始文件名的后缀 xxx.jpg
        String s = originalFilename.substring(originalFilename.lastIndexOf("."));
        // 构造新文件名称
        String objectName = UUID.randomUUID() + s;

        try {
            // Create a minioClient with the MinIO server playground, its access key and secret key.
            InputStream inputStream = file.getInputStream();

            MinioClient minioClient =
                    MinioClient.builder()
                            .endpoint(endpoint)
                            .credentials(accessKeyId, accessKeySecret)
                            .build();

            // Make 'asiatrip' bucket if not exist.
            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!found) {
                // Make a new bucket called 'asiatrip'.
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            }
            minioClient.putObject(
                    PutObjectArgs.builder().bucket(bucketName).object(objectName)
                            .stream(inputStream, file.getSize(), -1)
                            .contentType(MimeTypeUtils.IMAGE_JPEG_VALUE)
                            .build());
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // http://localhost:9000/sky-take-out/48f04e9e-de95-478d-b69b-906ec0
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder
                .append(endpoint)
                .append("/")
                .append(bucketName)
                .append("/")
                .append(objectName);
        log.info("文件路径:{}", stringBuilder);

        return stringBuilder.toString();
    }

}
